//* helper object to monitor how many images are being loaded, and how many yet to be loaded

// TODO: more friendly version should display only text "Loading" and only when it is displayed more than e.g. 500ms then show what is actually loading because now it is a bit fast, also when all is displayed let it be visible for some time and maybe fade out or something

function Loader() {
  this.stacker = new Array();
  
  this.normalize = function(AImageSrc) {
    // convert "bar.png" or "http://foo/bar.png" or "colorize?src=bar" to "bar"
    var s = AImageSrc.split('/').pop().replace('.png','');
    // colorize.php?r=192&g=478&b=206&image=hairstyle4
    if (s.match('colorize.php'))
      s = s.split('image=').pop();
    return s;    
  }
  
  this.push = function(AImageSrc) {
    // store which items is need to load
    AImageSrc = this.normalize(AImageSrc);
    ///debug('Loader.push: "'+AImageSrc+'"');
    this.stacker.push(AImageSrc);
  }
  
  this.pop = function(AImageSrc) {
    // when item is loaded, remove it from stacker
    AImageSrc = this.normalize(AImageSrc);
    ///debug('Loader.pop: "'+AImageSrc+'"');
    for (var i=0; i<this.stacker.length; i++)
    if (this.stacker[i] == AImageSrc) {
      this.stacker.splice(i,1);
      break;
    }
  }
  
  this.busy = function() {
    // return true if something is still being loaded
    return this.stacker.length > 0;
  }
  
  this.status = function() {
    // return human-readable info about what is loading
    //var last = this.stacker[this.stacker.length-1];
    var s = "Loading";
    if (this.stacker.length > 0) {
      s += ' '+(this.stacker.length)+' item';
      if (this.stacker.length > 1)
        s += 's';
    }
    return s;
  }
  
  this.draw = function() {
    // display loader info
    if (this.busy()) {
      // background dark rectangle
      context.fillStyle = "rgba(0,0,0,0.5)";
      context.fillRect(0,460,640,480);
      // label itself
      context.font = "bold 12pt courier";
      context.fillStyle = "rgba(255,255,0,0.8)";
      context.textAlign = "center";
      context.fillText(this.status(),320,460+16);
    }    
  }
  
}

loader = new Loader();